package com.ilovepostcard.view;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ilovepostcard.CommentActivity;
import com.ilovepostcard.R;
import com.ilovepostcard.UserActivity;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.Comment;
import com.ilovepostcard.model.Postcard;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.DrawableManager;
import com.ilovepostcard.utils.StringUtils;
import com.ilovepostcard.utils.Utils;
import com.mobclick.android.MobclickAgent;

public class PostcardDetailView extends LinearLayout {
    
    private Postcard postcard;
    
    private ImageView mLike;
    
    private View mComment;
    
    private ImageView mImage;
    
    private TextView mCreateDate;
    
    private TextView mCreateLocation;
    
    private TextView mTag;
    
    private ImageView mUserIcon;
    
    private TextView mUserNickName;
    
    private TextView mUserCardNumber;
    
    private Button mFollow;
    
    private View mFollowBtn;
    
    private EditText mCommentEdit;
    
    private Button mSendComment;
    
    private View mCommentRow;
    
    private TextView mCommentNickname;
    
    private TextView mCommentContent;
    
    private boolean mAttention;

    public PostcardDetailView(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate();
    }

    public PostcardDetailView(Context context) {
        super(context);
        inflate();
    }

    private void inflate() {
        View view = View.inflate(getContext(), R.layout.postcard_detail, this);
        mLike = (ImageView) view.findViewById(R.id.postcard_like);
        mComment = view.findViewById(R.id.postcard_comment);
        mImage = (ImageView) view.findViewById(R.id.postcard_image);
        mCreateDate = (TextView) view.findViewById(R.id.postcard_detail_create_date);
        mCreateLocation = (TextView) view.findViewById(R.id.postcard_detail_create_location);
        mTag = (TextView) view.findViewById(R.id.postcard_detail_tag);
        mUserIcon = (ImageView) view.findViewById(R.id.postcard_detail_user_icon);
        mUserNickName = (TextView) view.findViewById(R.id.postcard_detail_user_nickname);
        mUserCardNumber = (TextView) view.findViewById(R.id.postcard_detail_user_card_number);
        mFollow = (Button) view.findViewById(R.id.postcard_detail_follow);
        mFollowBtn = view.findViewById(R.id.postcard_detail_follow_btn);
        mCommentEdit = (EditText) view.findViewById(R.id.postcard_detail_comment_editview);
        mSendComment = (Button) view.findViewById(R.id.postcard_detail_send_comment);
        mCommentRow = view.findViewById(R.id.postcard_detail_comment_row);
        mCommentNickname = (TextView) mCommentRow.findViewById(R.id.comment_nickname);
        mCommentContent = (TextView) mCommentRow.findViewById(R.id.comment_content);
    }
    
    public void setPostcard(Postcard postcard) {
        this.postcard = postcard;
        post(new Runnable() {
            
            @Override
            public void run() {
                updateView();
            }
        });
    }
    
    private void updateView() {
        if (postcard == null)
            return;
        
        final User loginUser = UserController.getDetailUser(getContext());
        if (loginUser.UserID != postcard.UserID)
        {
	        new ServerAsyncTask(getContext()) {
	            
	            @Override
	            protected boolean isShowDialog() {
	                return false;
	            }
	            
	            @Override
	            protected void onSuccess(PostcardResult result) {
	                if (result.getCheckLike()) {
	                    mLike.setImageResource(R.drawable.discover_cardview_icon_digg_actived);
	                    mLike.setOnClickListener(new OnClickListener() {
	                        
	                        @Override
	                        public void onClick(View v) {
	                        	MobclickAgent.onEvent(PostcardDetailView.this.getContext(), Constants.COUNT_DISCOVER_WATCH_DIGG);
	                            Toast.makeText(getContext(), "已经称赞过了～", Toast.LENGTH_SHORT).show();
	                        }
	                    });
	                } else {
	                    mLike.setOnClickListener(new View.OnClickListener() {
	                        
	                        @Override
	                        public void onClick(View v) {
	                        	MobclickAgent.onEvent(PostcardDetailView.this.getContext(), Constants.COUNT_DISCOVER_WATCH_DIGG);
	                            if (postcard == null)
	                                return;
	                            new ServerAsyncTask(getContext()) {
	                                
	                                @Override
	                                protected void onSuccess(PostcardResult result) {
	                                    mLike.setImageResource(R.drawable.discover_cardview_icon_digg_actived);
	                                    mLike.setOnClickListener(new OnClickListener() {
	                                        
	                                        @Override
	                                        public void onClick(View v) {
	                                        	MobclickAgent.onEvent(PostcardDetailView.this.getContext(), Constants.COUNT_DISCOVER_WATCH_DIGG);
	                                            Toast.makeText(getContext(), "已经称赞过了～", Toast.LENGTH_SHORT).show();
	                                        }
	                                    });
	                                    Toast.makeText(getContext(), R.string.success_like, Toast.LENGTH_SHORT).show();
	                                }
	                                
	                                @Override
	                                protected PostcardResult doRequest() {
	                                    User user = UserController.getLoginUser(getContext());
	                                    return ServerFactory.getServer().likePostcard(user.UserID, postcard.PostcardID);
	                                }
	                            }.execute();
	                        }
	                    });
	                }
	            }
	            
	            @Override
	            protected PostcardResult doRequest() {
	                return ServerFactory.getServer().checkLike(loginUser.UserID, postcard.PostcardID);
	            }
	        }.execute();
        }
        
        
        mComment.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
            	
            	MobclickAgent.onEvent(PostcardDetailView.this.getContext(), Constants.COUNT_DISCOVER_WATCH_COMMENT);
                if (postcard == null)
                    return;
                Intent intent = new Intent(getContext(), CommentActivity.class);
                intent.putExtra("pid", postcard.PostcardID);
                getContext().startActivity(intent);
            }
        });
        
        if (postcard.Status == 1) {
            mImage.setImageResource(R.drawable.discover_card_deleted);
        } else {
            DrawableManager.getInstance().fetchDrawableOnThread(postcard.PerviewImgUrl, mImage);
        }
        
        mCreateDate.setText("创作时间：" + postcard.PublishTime);
        String location = postcard.Location;
        if (StringUtils.isEmpty(location) || "null".equals(location)) {
            location = "地球某区域";
        }
        if (postcard.LocationPermission == 1) {
            location = "保密";
        }
        mCreateLocation.setText("拍摄地点：" + location);
        mTag.setText("标        签：" + (StringUtils.isNotBlank(postcard.TagIn) ? postcard.TagIn : "没有标签"));
        
        
        
        if (loginUser.UserID != postcard.UserID) {
            new ServerAsyncTask(getContext()) {

                @Override
                protected void onSuccess(PostcardResult result) {
                    final User user = result.getUser();
                    if (user != null) {
                        mUserNickName.setText(user.Nickname);
                        mUserCardNumber.setText("创建明信片：" + user.PublishCount);
                        mUserIcon
                                .setOnClickListener(new View.OnClickListener() {

                                    @Override
                                    public void onClick(View v) {
                                    	
                                    	MobclickAgent.onEvent(PostcardDetailView.this.getContext(), Constants.COUNT_DISCOVER_WATCH_SPACE);
                                        Intent intent = new Intent(
                                                getContext(),
                                                UserActivity.class);
                                        intent.putExtra("user", user);
                                        intent.putExtra("attention", mAttention);
                                        getContext().startActivity(intent);
                                    }
                                });
                        if (user.HasHeadImg)
                            DrawableManager.getInstance()
                                    .fetchDrawableOnThread(user.HeadImgUrl,
                                            mUserIcon, false);

                        /* 关注状态 */
                        new ServerAsyncTask(getContext()) {

                            @Override
                            protected boolean isShowDialog() {
                                return false;
                            }

                            @Override
                            protected void onSuccess(PostcardResult result) {
                                boolean attention = result.getCheckAttention();
                                mAttention = attention;
                                mFollow.setVisibility(attention ? VISIBLE
                                        : GONE);
                                mFollowBtn.setVisibility(attention ? GONE
                                        : VISIBLE);
                                if (!attention) {
                                    mFollowBtn
                                            .setOnClickListener(new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    new ServerAsyncTask(
                                                            getContext()) {

                                                        @Override
                                                        protected void onSuccess(
                                                                PostcardResult result) {
                                                            mAttention = true;
                                                            mFollow.setVisibility(VISIBLE);
                                                            mFollowBtn
                                                                    .setVisibility(GONE);
                                                            Toast.makeText(
                                                                    getContext(),
                                                                    R.string.success_attention,
                                                                    Toast.LENGTH_SHORT)
                                                                    .show();
                                                        }

                                                        @Override
                                                        protected PostcardResult doRequest() {
                                                            return ServerFactory
                                                                    .getServer()
                                                                    .attention(
                                                                            loginUser.UserID,
                                                                            user.UserID,
                                                                            IServer.ATTENTION_TYPE_FOLLOW);
                                                        }
                                                    }.execute();
                                                }

                                            });
                                }
                            }

                            @Override
                            protected PostcardResult doRequest() {
                                return ServerFactory.getServer()
                                        .checkAttention(loginUser.UserID,
                                                user.UserID);
                            }
                        }.execute();
                    } else {
                        Toast.makeText(getContext(), "获取用户信息失败",
                                Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                protected PostcardResult doRequest() {
                    return ServerFactory.getServer().getUserInfo("",
                            postcard.UserID);
                }
            }.execute();
        } else {
            final User user = loginUser;
            if (user != null) {
                mUserNickName.setText(user.Nickname);
                mUserCardNumber.setText("创建明信片：" + user.PublishCount);
                mUserIcon
                        .setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(
                                        getContext(),
                                        UserActivity.class);
                                intent.putExtra("user", user);
                                intent.putExtra("attention", mAttention);
                                getContext().startActivity(intent);
                            }
                        });
                if (user.HasHeadImg)
                    DrawableManager.getInstance()
                            .fetchDrawableOnThread(user.HeadImgUrl,
                                    mUserIcon, false);
            }
        }
        
        new ServerAsyncTask(getContext()) {
            
            @Override
            protected boolean isShowDialog() {
                return false;
            }
            
            @Override
            protected void onSuccess(PostcardResult result) {
                Comment comment = result.getLastPostcardComment();
                if (comment != null) {
                    mCommentRow.setVisibility(VISIBLE);
                    mCommentEdit.setVisibility(GONE);
                    mSendComment.setVisibility(GONE);
                    mCommentNickname.setText(loginUser.Nickname+"：");
                    mCommentContent.setText(comment.Body);
                }
            }
            
            @Override
            protected PostcardResult doRequest() {
                return ServerFactory.getServer().getLastPostcardComment(loginUser.UserID, postcard.PostcardID);
            }
        }.execute();
        
        mSendComment.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                String commentString = mCommentEdit.getText().toString();
                commentString = commentString.trim();
                if (StringUtils.isEmpty(commentString))
                    return;
                final String body = commentString;
                if (!Utils.isCommentLegal(getContext(), body)) {
                    Toast.makeText(getContext(), "内容含有敏感信息，不能发布。", Toast.LENGTH_SHORT).show();
                    return;
                }
                new ServerAsyncTask(getContext()) {
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        mCommentEdit.setText("");
                        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mCommentEdit.getWindowToken(), 0);
                        Toast.makeText(context, R.string.success_comment, Toast.LENGTH_SHORT).show();
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().newPostcardComment(loginUser.UserID, postcard.PostcardID, body);
                    }
                }.execute();
            }
        });
    }
}
